namespace EyeOpen.SampleCms.Web
{
    using System;
    using System.Configuration;
    using System.IO;
    using System.Web;
    using EyeOpen.SampleCms.Web.Contents;

    public static class ConfigurationWrapper
    {
        public static string PagePath
        {
            get
            {
                var isHome = 
                    VirtualPathUtility
                        .ToAppRelative(HttpContext.Current.Request.Path)
                            .Equals("~/default.aspx", StringComparison.InvariantCultureIgnoreCase);

                var existPhysical = File.Exists(HttpContext.Current.Request.PhysicalPath);

                var usePhysicalPath = existPhysical && !isHome;

                if (usePhysicalPath)
                {
                    return VirtualPathUtility.ToAppRelative(HttpContext.Current.Request.Path);
                }

                if ((!HttpContext.Current.Request.IsAuthenticated) && (!string.IsNullOrEmpty(SectionContents.CurrentSectionContent.PagePath)))
                {
                    return SectionContents.CurrentSectionContent.PagePath;
                }
             
                return GetValue("DefaultPage");
            }
        }

        public static string SectionContentProvider
        {
            get
            {
                return GetValue("SectionContentProvider");
            }
        }

        public static string ContentsPath
        {
            get
            {
                return GetValue("ContentsPath");
            }
        }

        public static string[] Pages
        {
            get
            {
                var pages = GetValue("Pages");

                if (string.IsNullOrEmpty(pages))
                {
                    return null;
                }

                pages = pages.TrimEnd(";".ToCharArray());
                return pages.Split(";".ToCharArray());
            }
        }

        private static string GetValue(string key)
        {
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings[key]))
            {
                return string.Empty;
            }

            return ConfigurationManager.AppSettings[key];
        }
    }
}